<script setup>
import { useRouter } from 'vue-router';
import { ref, reactive, nextTick } from 'vue';
import { ElMessage, ElDialog } from 'element-plus';
import { UserRegisterService, UserLoginService } from '@/api/user';
import { useTokenStore } from '@/stores/token';
import { useUserStore } from '@/stores/user';
import { UserFilled, Male, Female, ArrowRight } from '@element-plus/icons-vue';

const userStore = useUserStore();
const tokenStore = useTokenStore();
const router = useRouter();

const goToLogin = () => {
  router.push('/login');
}

const registerData = ref({
  username: '',
  password: '',
  rePassword: '',
  fullName: '',
  sex: '',
  age: '',
  height: '',
  weight: ''
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*\d)[a-z\d]{8,20}$/,
      message: '用户名必须是8-20位,并且包含小写字母和数字',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度必须大于8位', trigger: 'blur' }
  ],
  rePassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerData.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
})

const validateUsername = (username) => {
  const regex = /^(?=.*[a-z])(?=.*\d)[a-z\d]{8,20}$/;
  return regex.test(username);
}

const validatePassword = (password) => {
  return password.length >= 8;
}

const validateUsernameOnBlur = () => {
  if (!validateUsername(registerData.value.username)) {
    ElMessage.error('用户名必须是8-20位,并且包含小写字母和数字');
    return false;
  }
  return true;
}

const validatePasswordOnBlur = () => {
  if (!validatePassword(registerData.value.password)) {
    ElMessage.error('密码长度必须大于8位');
    return false;
  }
  return true;
}

const validateRePasswordOnBlur = () => {
  if (registerData.value.password !== registerData.value.rePassword) {
    ElMessage.error('两次输入的密码不一致');
    return false;
  }
  return true;
}

const register = async () => {
  // 再次验证所有字段
  if (!validateUsernameOnBlur() || !validatePasswordOnBlur() || !validateRePasswordOnBlur()) {
    return;
  }

  let result = await UserRegisterService({
    username: registerData.value.username,
    password: registerData.value.password,
    rePassword: registerData.value.rePassword
  });
  
  if (result.code == 200) 
  {
    ElMessage.success('账号创建成功，请完善个人信息');
    showUserInfoDialog.value = true;
  } else 
  {
    ElMessage.error(result.message);
  }
}

const showUserInfoDialog = ref(false);

// 添加表单验证规则
const userInfoRules = reactive({
  fullName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在1-120岁之间', trigger: 'blur' }
  ],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' },
    { type: 'number', min: 50, max: 250, message: '身高必须在50-250cm之间', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' },
    { type: 'number', min: 20, max: 200, message: '体重必须在20-200kg之间', trigger: 'blur' }
  ]
})

// 添加表单ref
const userInfoFormRef = ref(null)

// 添加 loading 状态
const loading = ref(false)

// 修改 saveUserInfo 方法
const saveUserInfo = async () => {
  if (!userInfoFormRef.value) return
  
  try {
    loading.value = true
    await userInfoFormRef.value.validate()
    
    // 验证通过后继续处理
    let result = await UserRegisterService(registerData.value)
    if (result.code == 200) {
      // 注册成功后自动登录
      let loginResult = await UserLoginService({
        username: registerData.value.username,
        password: registerData.value.password
      })
      
      if (loginResult.code == 200) {
        showUserInfoDialog.value = false
        tokenStore.setToken(loginResult.data.token)
        userStore.setUserInfo(loginResult.data)
        ElMessage.success('注册成功并已登录')
        
        setTimeout(() => {
          router.push('/')
        }, 100)
      } else {
        ElMessage.error('注册成功但自动登录失败，请手动登录')
        showUserInfoDialog.value = false
        setTimeout(() => {
          router.push('/login')
        }, 100)
      }
    } else {
      ElMessage.error(result.message || '保存失败')
    }
  } catch (error) {
    // 表单验证失败或其他错误
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('请填写完整的个人信息')
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="container">
    <div class="register_box">
      <div class="image_box">
        <img src="@/assets/hsa.jpg" alt="background">
      </div>
      <div class="form_box">
        <form class="form" :model="registerData" :rules="rules" @submit.prevent="register">
          <div class="logo_container">
            <img src="@/assets/wsylogo.svg" alt="logo" style="width: 100%; height: 100%; object-fit: contain;">
          </div>
          <div class="title_container">
            <p class="title">注册账号</p>
            <span class="subtitle">创建一个账号开始使用我们的服务</span>
          </div>
          <br>
          <div class="input_container">
            <label class="input_label" for="username_field">用户名</label>
            <svg fill="none" viewBox="0 0 24 24" height="24" width="24" xmlns="http://www.w3.org/2000/svg" class="icon">
              <path stroke-linejoin="round" stroke-linecap="round" stroke-width="1.5" stroke="#141B34"
                d="M7 8.5L9.94202 10.2394C11.6572 11.2535 12.3428 11.2535 14.058 10.2394L17 8.5"></path>
              <path stroke-linejoin="round" stroke-width="1.5" stroke="#141B34"
                d="M2.01577 13.4756C2.08114 16.5412 2.11383 18.0739 3.24496 19.2094C4.37608 20.3448 5.95033 20.3843 9.09883 20.4634C11.0393 20.5122 12.9607 20.5122 14.9012 20.4634C18.0497 20.3843 19.6239 20.3448 20.7551 19.2094C21.8862 18.0739 21.9189 16.5412 21.9842 13.4756C22.0053 12.4899 22.0053 11.5101 21.9842 10.5244C21.9189 7.45886 21.8862 5.92609 20.7551 4.79066C19.6239 3.65523 18.0497 3.61568 14.9012 3.53657C12.9607 3.48781 11.0393 3.48781 9.09882 3.53656C5.95033 3.61566 4.37608 3.65521 3.24495 4.79065C2.11382 5.92608 2.08114 7.45885 2.01576 10.5244C1.99474 11.5101 1.99475 12.4899 2.01577 13.4756Z">
              </path>
            </svg>
            <input placeholder="请输入用户名(8-20位,包含小写字母和数字)" v-model="registerData.username" @blur="validateUsernameOnBlur"
              title="Input title" name="input-name" type="text" class="input_field" id="username_field">
          </div>
          <div class="input_container">
            <label class="input_label" for="password_field">密码</label>
            <svg fill="none" viewBox="0 0 24 24" height="24" width="24" xmlns="http://www.w3.org/2000/svg" class="icon">
              <path stroke-linecap="round" stroke-width="1.5" stroke="#141B34"
                d="M18 11.0041C17.4166 9.91704 16.273 9.15775 14.9519 9.0993C13.477 9.03404 11.9788 9 10.329 9C8.67911 9 7.18091 9.03404 5.70604 9.0993C3.95328 9.17685 2.51295 10.4881 2.27882 12.1618C2.12602 13.2541 2 14.3734 2 15.5134C2 16.6534 2.12602 17.7727 2.27882 18.865C2.51295 20.5387 3.95328 21.8499 5.70604 21.9275C6.42013 21.9591 7.26041 21.9834 8 22">
              </path>
              <path stroke-linejoin="round" stroke-linecap="round" stroke-width="1.5" stroke="#141B34"
                d="M6 9V6.5C6 4.01472 8.01472 2 10.5 2C12.9853 2 15 4.01472 15 6.5V9"></path>
            </svg>
            <input placeholder="请输入密码(至少8位)" v-model="registerData.password" @blur="validatePasswordOnBlur"
              title="Input title" name="input-name" type="password" class="input_field" id="password_field">
          </div>
          <div class="input_container">
            <label class="input_label" for="confirm_password_field">确认密码</label>
            <svg fill="none" viewBox="0 0 24 24" height="24" width="24" xmlns="http://www.w3.org/2000/svg" class="icon">
              <path stroke-linecap="round" stroke-width="1.5" stroke="#141B34"
                d="M18 11.0041C17.4166 9.91704 16.273 9.15775 14.9519 9.0993C13.477 9.03404 11.9788 9 10.329 9C8.67911 9 7.18091 9.03404 5.70604 9.0993C3.95328 9.17685 2.51295 10.4881 2.27882 12.1618C2.12602 13.2541 2 14.3734 2 15.5134C2 16.6534 2.12602 17.7727 2.27882 18.865C2.51295 20.5387 3.95328 21.8499 5.70604 21.9275C6.42013 21.9591 7.26041 21.9834 8 22">
              </path>
              <path stroke-linejoin="round" stroke-linecap="round" stroke-width="1.5" stroke="#141B34"
                d="M6 9V6.5C6 4.01472 8.01472 2 10.5 2C12.9853 2 15 4.01472 15 6.5V9"></path>
            </svg>
            <input placeholder="请再次输入密码" v-model="registerData.rePassword" @blur="validateRePasswordOnBlur"
              title="Input title" name="input-name" type="password" class="input_field" id="confirm_password_field">
          </div>
          <button title="Register" type="submit" class="submit">
            <span>注册</span>
          </button>
          <button type="button" class="signin_btn" @click="goToLogin">
            <span>已有账号? 立即登录</span>
          </button>
        </form>
      </div>
    </div>
  </div>

  <!-- 修改用户信息对话框 -->
  <el-dialog
    v-model="showUserInfoDialog"
    title="完善个人信息"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    custom-class="user-info-dialog"
  >
    <div class="dialog-header-content">
      <div class="dialog-icon">
        <el-icon><UserFilled /></el-icon>
      </div>
      <h3 class="dialog-title">个人信息</h3>
      <p class="dialog-subtitle">请填写您的基本信息，帮助我们为您提供更好的服务</p>
    </div>

    <el-form
      ref="userInfoFormRef"
      :model="registerData"
      :rules="userInfoRules"
      label-position="top"
      class="user-info-form"
    >
      <el-form-item label="昵称" prop="fullName">
        <el-input
          v-model="registerData.fullName"
          placeholder="请输入昵称"
          :prefix-icon="User"
        />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-select
          v-model="registerData.sex"
          placeholder="请选择性别"
          class="w-full"
        >
          <el-option label="男" value="男">
            <template #prefix>
              <el-icon><Male /></el-icon>
            </template>
          </el-option>
          <el-option label="女" value="女">
            <template #prefix>
              <el-icon><Female /></el-icon>
            </template>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input-number
          v-model="registerData.age"
          :min="1"
          :max="120"
          class="w-full"
          placeholder="年龄"
        >
          <template #prefix>岁</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="身高" prop="height">
        <el-input-number
          v-model="registerData.height"
          :min="50"
          :max="250"
          class="w-full"
          placeholder="身高"
        >
          <template #prefix>cm</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="体重" prop="weight">
        <el-input-number
          v-model="registerData.weight"
          :min="20"
          :max="200"
          class="w-full"
          placeholder="体重"
        >
          <template #prefix>kg</template>
        </el-input-number>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button 
          type="primary" 
          class="submit-button" 
          @click="saveUserInfo"
          :loading="loading"
        >
          完成注册
          <el-icon class="el-icon--right"><ArrowRight /></el-icon>
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.register_box {
  width: 1000px;
  height: 600px;
  position: relative;
  display: flex;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.image_box {
  flex: 1.309;
  overflow: hidden;
}

.image_box img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.form_box {
  flex: 1.2;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
}

.form {
  width: 100%;
  max-width: 400px;
  height: fit-content;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 15px;
  padding: 20px;
}

.logo_container {
  box-sizing: border-box;
  width: 80px;
  height: 80px;
  background: linear-gradient(180deg, rgba(248, 248, 248, 0) 50%, #F8F8F888 100%);
  border: 1px solid #F7F7F8;
  filter: drop-shadow(0px 0.5px 0.5px #EFEFEF) drop-shadow(0px 1px 0.5px rgba(239, 239, 239, 0.5));
  border-radius: 11px;
}

.title_container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
  color: #212121;
}

.subtitle {
  font-size: 0.875rem;
  max-width: 80%;
  text-align: center;
  line-height: 1.4;
  color: #8B8E98
}

.input_container {
  width: 100%;
  height: fit-content;
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.icon {
  width: 20px;
  position: absolute;
  z-index: 99;
  left: 12px;
  bottom: 12px;
}

.input_label {
  font-size: 0.875rem;
  color: #8B8E98;
  font-weight: 600;
}

.input_field {
  width: 100%;
  height: 40px;
  padding: 0 15px 0 45px;
  border-radius: 7px;
  outline: none;
  border: 1px solid #e5e5e5;
  filter: drop-shadow(0px 1px 0px #efefef) drop-shadow(0px 1px 0.5px rgba(239, 239, 239, 0.5));
  transition: all 0.3s cubic-bezier(0.15, 0.83, 0.66, 1);
}

.input_field:focus {
  border: 1px solid transparent;
  box-shadow: 0px 0px 0px 2px #242424;
  background-color: transparent;
}

.submit {
  width: 100%;
  height: 40px;
  border: 0;
  background: #115DFC;
  border-radius: 7px;
  outline: none;
  color: #ffffff;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 5px;
}

.signin_btn {
  width: 100%;
  height: 40px;
  border: 1px solid #115DFC;
  background: transparent;
  border-radius: 7px;
  outline: none;
  color: #115DFC;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 1rem;
}

.signin_btn:hover {
  background: #115DFC;
  color: #ffffff;
}

/* 添加用户信息表单的样式 */
.user-info-form {
  padding: 30px;
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  padding-top: 20px;
}

/* 修改 select 样式以匹配输入框 */
select.input_field {
  padding: 0 15px;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 1rem center;
  background-size: 1em;
}

/* 对话框动画 */
:deep(.el-dialog) {
  transform: scale(0.9);
  transition: all 0.3s ease-in-out;
}

:deep(.el-dialog.el-dialog--center) {
  transform: scale(1);
}

/* 对话框样式优化 */
.user-info-dialog {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  display: none;
}

:deep(.el-dialog__body) {
  padding: 0;
}

.dialog-header-content {
  background: linear-gradient(135deg, #4263eb 0%, #6d8dff 100%);
  padding: 30px;
  text-align: center;
  color: white;
  position: relative;
}

.dialog-icon {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
  font-size: 30px;
}

.dialog-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px;
}

.dialog-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.user-info-form {
  padding: 30px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 调整数字输入框的宽度 */
:deep(.el-input-number) {
  width: 100%;
}

/* 调整表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 最后一个表单项不需要底部间距 */
:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.el-input__wrapper),
:deep(.el-input-number__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

.submit-button {
  width: 200px;
  height: 40px;
  background: linear-gradient(135deg, #4263eb 0%, #6d8dff 100%);
  border: none;
  font-weight: 500;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.submit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 99, 235, 0.3);
}

.submit-button:active {
  transform: translateY(0);
}

/* 适配移动端 */
@media screen and (max-width: 640px) {
  .user-info-dialog {
    width: 90% !important;
  }
}
</style>
